$(document).ready(function () {

    // 搜索按钮
    $("#search").on('click', function (e) {
        //重置页码
        $("#webPage").val(1);
        //查询数据
        loadData();
    });

    // 添加账号
    $(".addAccount").on('click', function (e) {
        //清空内容
        $("#loginUser").val("");
        $("#loginPassword").val("");
        $("#name").val("");
        $("#phone").val("");
        //弹出窗口
        $('#addAccountDiv').modal('show');
        //默认选中添加监督员
        $("[name='roleId'][value='2']").prop("checked", "checked");
        addInspector();
    });

    // 添加账号-身份变更
    $("[name='roleId']").on('change', function (e) {
        let roleId = $("[name='roleId']:checked").val();
        if (roleId == 1) {
            //添加管理员
            addAdmin();
        } else {
            //添加监察员
            addInspector();
        }
    });

    //监督员添加监管机构
    $("#confirmInstitution").on('click', function (e) {
        //获取选中机构

        let institutionName = $("#institutionName").val();
        if (!institutionName) {
            WeKnow.notifyMsg('请选择机构');
            return
        }
        let selectOption = $("#inspectorPowerSelect option[value=" + institutionName + "]");
        if (!$("#inspectorPowerSelect option[value=" + institutionName + "]").text()) {
            WeKnow.notifyMsg('必须在下拉框里选着机构');
            return
        }
        //添加监管机构到页面
        let ListDiv = $(".confirmInstitutionListDiv");
        let html = '<div class="confirmInstitutionDiv">'
            + '<input type="text" class="inspectorPowerIpt" readonly value="' + selectOption.html() + '">'
            + '<input class="btn btn-primary confirmInstitution" name="removeInstitution" '
            + 'data-institution_id="' + selectOption.data("healinstitution_id") + '" '
            + 'data-address_id="' + selectOption.data("institution_id") + '" '
            + 'data-province="' + selectOption.data("province") + '" '
            + 'data-city="' + selectOption.data("city") + '" '
            + 'data-county="' + selectOption.data("county") + '" '
            + 'data-name="' + selectOption.html() + '" '
            + 'type="button" value="×">'
            + '</div>';
        ListDiv.append(html);
        //从下拉列表中删除
        selectOption.remove();
        $("#institutionName").val("");
    });

    //监督员删除监管机构
    $(".confirmInstitutionListDiv").on('click', '[name="removeInstitution"]', function (e) {
        let that = $(this);
        //确认框
        WeKnow.confirm("确认去除这个监管机构吗？", function () {
            //添加删除的机构到下拉列表
            let html = "<option value='" + that.data("name") + "' "
                + "data-healinstitution_id='" + that.data("institution_id") + "' "
                + "data-institution_id='" + that.data("address_id") + "' "
                + "data-province='" + that.data("province") + "' "
                + "data-city='" + that.data("city") + "' "
                + "data-county='" + that.data("county") + "'>"
                + that.data("name") + "</option>";
            //设置内容
            $("#inspectorPowerSelect").append(html);
            //删除当前
            that.parent(".confirmInstitutionDiv").remove();
        });
    });

    //监督员添加监管机构(编辑)
    $("#confirmInstitutionUpdate").on('click', function (e) {
        //获取选中机构
        let institutionName = $("#institutionNameUpdate").val();
        if (!institutionName) {
            WeKnow.notifyMsg('请选择机构');
            return
        }
        let selectOption = $("#inspectorPowerSelectUpdate option[value=" + institutionName + "]");
        if (!$("#inspectorPowerSelectUpdate option[value=" + institutionName + "]").text()) {
            WeKnow.notifyMsg('必须在下拉框里选着机构');
            return
        }

        //判断加入机构是否存在
        let institutionList = $("[name='removeInstitution']");
        if (institutionList) {
            for (let i = 0; i < institutionList.length; i++) {
                let institution = $(institutionList[i]);
                let institutionId1=institution.data("institution_id");
                let institutionId2=selectOption.data("healinstitution_id")
                if(institutionId1==institutionId2){
                    WeKnow.notifyMsg('该机构已加入');
                    return
                }
            }
        }

        //添加监管机构到页面
        let ListDiv = $(".confirmInstitutionListDivUpdate");
        let html = '<div class="confirmInstitutionDiv">'
            + '<input type="text" class="inspectorPowerIpt" readonly value="' + selectOption.html() + '">'
            + '<input class="btn btn-primary confirmInstitution" name="removeInstitution" '
            + 'data-institution_id="' + selectOption.data("healinstitution_id") + '" '
            + 'data-address_id="' + selectOption.data("institution_id") + '" '
            + 'data-province="' + selectOption.data("province") + '" '
            + 'data-city="' + selectOption.data("city") + '" '
            + 'data-county="' + selectOption.data("county") + '" '
            + 'data-name="' + selectOption.html() + '" '
            + 'type="button" value="×">'
            + '</div>';
        ListDiv.append(html);
        //从下拉列表中删除
        selectOption.remove();
        $("#institutionNameUpdate").val("");
    });

    //监督员删除监管机构(编辑)
    $(".confirmInstitutionListDivUpdate").on('click', '[name="removeInstitution"]', function (e) {
        let that = $(this);
        //确认框
        WeKnow.confirm("确认去除这个监管机构吗？", function () {
            //添加删除的机构到下拉列表
            let html = "<option value='" + that.data("name") + "' "
                + "data-healinstitution_id='" + that.data("institution_id") + "' "
                + "data-institution_id='" + that.data("address_id") + "' "
                + "data-province='" + that.data("province") + "' "
                + "data-city='" + that.data("city") + "' "
                + "data-county='" + that.data("county") + "'>"
                + that.data("name") + "</option>";
            //设置内容
            $("#inspectorPowerSelectUpdate").append(html);
            //删除当前
            that.parent(".confirmInstitutionDiv").remove();
        });
    });


    //保存添加账号
    $("#saveAccountButton").on('click', function (e) {
        saveAccount();
    });


    //保存修改账号
    $("#updateAccountButton").on('click', function (e) {
        updateAccount();
    });


    //绑定App账号
    $("#bindAccountButton").on('click', function (e) {
        bindAccount();
    });


    //删除
    $("#tbodyAccountManageList").on('click', '.deleteSpan', function (e) {
        //获取数据
        let $parentTr = $(this).closest('tr');
        //确认框
        WeKnow.confirm("确认删除这个账号吗？", function () {
            //获取数据
            let supervisorId = $parentTr.data('supervisor_id');
            //请求接口
            deleteAccount(supervisorId);
        });
    });

    //编辑
    $("#tbodyAccountManageList").on('click', '.updateSpan', function (e) {
        //获取数据
        let $parentTr = $(this).closest('tr');
        //保存当前编辑部分信息
        $("#updateAccountId").val($parentTr.data('supervisor_id'));
        $("#updateRoleId").val($parentTr.data('role_id'));
        //判断身份
        if ($parentTr.data('role_id') == 1) {
            //管理员
            addAdmin();
            //选中当前权限区域
            $(".adminPowerSelectUpdate").val($parentTr.data('institution_id'));
        } else {
            //督察员
            addInspector();
            //获取当前权限机构
            getJurisdictionInstitution($parentTr.data('supervisor_id'));
        }
        //弹出编辑框
        $('#updateAccountDiv').modal('show');
    });

    //重置密码
    $("#tbodyAccountManageList").on('click', '.resetPasswordSpan', function (e) {
        //获取数据
        let $parentTr = $(this).closest('tr');
        //确认框
        WeKnow.confirm("确认将这个账号的密码重置为'123456'吗？", function () {
            //获取数据
            let supervisorId = $parentTr.data('supervisor_id');
            //请求接口
            resetPassword(supervisorId);
        });
    });


    //绑定
    $("#tbodyAccountManageList").on('click', '.bindSpan', function (e) {
        //获取数据
        let $parentTr = $(this).closest('tr');
        $("#bindSupervisorId").val($parentTr.data('supervisor_id'));
        //弹出编辑框
        $('#bindAccountDiv').modal('show');
    });

    //加载数据
    loadData();
});

//总页数
let allPage = 1;

//加载数据
function loadData() {
    //获取请求参数
    let loadParams = getLoadParams();
    WeKnow.loading();
    //请求接口
    $.ajax({
        type: "POST",
        url: "accountManage.do/list",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(loadParams),
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode === 1) {
                let $orgBody = $('#tbodyAccountManageList');
                $orgBody.empty();
                let dataInfo = data.dataInfo;
                if (dataInfo && dataInfo.length) {
                    let e = '';
                    $(dataInfo).each(function (idx, rowData) {
                        e += '<tr data-supervisor_id="' + rowData.supervisorId + '" data-role_id="' + rowData.roleId + '" data-institution_id="' + rowData.institutionId + '" >';
                        // 账号名称
                        e += '<td class="text-center">' + (rowData.loginUser ? rowData.loginUser : "-") + '</td>';
                        // 姓名
                        e += '<td class="text-center">' + (rowData.name ? rowData.name : "-") + '</td>';
                        // 手机
                        e += '<td class="text-center">' + (rowData.phone ? rowData.phone : "-") + '</td>';
                        // 管理员
                        if (rowData.roleId == 1) {
                            e += '<td class="text-center">是</td>';
                        } else {
                            e += '<td class="text-center">否</td>';
                        }
                        // 操作
                        e += '<td class="text-center">';
                        e += '<a href="#"><span class="deleteSpan">删除</span></a>';
                        e += '<a href="#"><span class="updateSpan">编辑</span></a>';
                        e += '<a href="#"><span class="resetPasswordSpan">重置密码</span></a>';
                        if (rowData.wxUserId == -1) {
                            e += '<a href="#"><span class="bindSpan">未绑定</span></a>';
                        } else {
                            e += '<a style="pointer-events: none;"><span class="unBindSpan">已绑定</span></a>';
                        }
                        e += '</td>';
                        e += '</tr>';
                    });
                    $orgBody.append(e);
                } else {
                    WeKnow.notifyMsg('暂无数据');
                }
                //页码修改
                if (allPage != data.pages) {
                    allPage = data.pages;
                    //重新生成页面下拉
                    let $selectPage = $('#selectPage');
                    $selectPage.empty();
                    let e = '';
                    for (let i = 1; i <= allPage; i++) {
                        e += '<option value="' + i + '">' + i + '</option>';
                    }
                    $selectPage.append(e);
                    //总页码
                    $(".allPage").html("共" + allPage + "页");
                }
                //限制上一页
                if (loadParams.pageNum == 1) {
                    $(".upPageDiv").html('上一页');
                } else {
                    $(".upPageDiv").html('<a href="javascript:updatePage(' + (parseInt(loadParams.pageNum) - 1) + ')">上一页</a>');
                }
                //限制下一页
                if (loadParams.pageNum >= allPage) {
                    $(".downPageDiv").html('下一页');
                } else {
                    $(".downPageDiv").html('<a href="javascript:updatePage(' + (parseInt(loadParams.pageNum) + 1) + ')">下一页</a>');
                }
                //修改当前页码
                $("#selectPage").val(loadParams.pageNum);
            } else if (data.errCode === -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }, complete: function () {
            WeKnow.closeLoading();
        }
    });

}

//获取 加载数据集合 入参
function getLoadParams() {
    let params = {};
    //账号名称
    params.userName = $("#userName").val();
    //页面
    params.pageNum = $("#pageNum").val();
    //一页数据加载数(limit)
    params.pageSize = $("#pageSize").val();
    return params;
}

//页面变更
$("#selectPage").on('change', function (e) {
    updatePage($(this).val())
});
//limit变更
$("#pageSize").on('change', function (e) {
    //重置页码
    $("#pageNum").val(1);
    //查询数据
    loadData();
});

//修改页码
function updatePage(pageNum) {
    //获取页码
    $("#pageNum").val(pageNum);
    //查询数据
    loadData();
}

//删除账号
function deleteAccount(supervisorId) {
    WeKnow.loading();
    $.ajax({
        type: "POST",
        url: "accountManage.do/delete",
        dataType: "json",
        data: {
            "supervisorId": supervisorId
        },
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //请求成功刷新页面
                window.location.reload();
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });
}

//重置密码
function resetPassword(supervisorId) {
    WeKnow.loading();
    $.ajax({
        type: "POST",
        url: "accountManage.do/resetPassword",
        dataType: "json",
        data: {
            "supervisorId": supervisorId
        },
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //请求成功
                WeKnow.successMsg("操作成功");
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });
}

let regionList = [];

//添加管理员 权限内容填充
function addAdmin() {
    //填充显示变更
    $(".adminPowerDiv").show();
    $(".inspectorPowerDiv").hide();
    $("[name='jurisdiction']").html("管辖区域：");
    //填充内容
    if (regionList.length == 0) {
        //请求数据 后填充
        getRegion();
    } else {
        //直接填充
        resetRegion()
    }
}

//获取权限区域
function getRegion() {
    WeKnow.loading();
    //从数据库获取所属区域
    $.ajax({
        type: "POST",
        url: "accountManage.do/getRegion",
        dataType: "json",
        async: false,//同步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //请求成功遍历添加
                regionList = data.regionList;
                //重新填充权限区域
                resetRegion();
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });
}

//重新填充权限区域
function resetRegion() {
    let e = "";
    for (let index in regionList) {
        let region = regionList[index];
        //拼接option
        e += "<option value='" + region.id + "' >" + region.name + "</option>";
    }
    //设置内容
    $(".adminPowerSelect").html(e);
    $(".adminPowerSelectUpdate").html(e);
}

let institutionList = [];

//添加监察员 权限内容填充
function addInspector() {
    //填充显示变更
    $(".inspectorPowerDiv").show();
    $(".adminPowerDiv").hide();
    $("[name='jurisdiction']").html("管辖机构：");
    //填充内容
    if (institutionList.length == 0) {
        //请求数据 后填充
        getInstitution();
    } else {
        //直接填充
        resetInstitution()
    }
}

//获取权限机构
function getInstitution() {
    WeKnow.loading();
    //从数据库获取所属区域
    $.ajax({
        type: "POST",
        url: "accountManage.do/getInstitution",
        dataType: "json",
        async: false,//同步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //请求成功遍历添加
                institutionList = data.institutionList;
                resetInstitution();
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });
}

//重新填充权限机构
function resetInstitution() {
    //清除选中
    $(".confirmInstitutionListDiv").html("");
    //重新填充
    let e = "";
    for (let index in institutionList) {
        let institution = institutionList[index];
        //拼接option
        $("#inspectorPowerSelect").append("<option value='" + institution.name + "' "
            + "data-healinstitution_id='" + institution.id + "' "
            + "data-institution_id='" + institution.institutionId + "' "
            + "data-province='" + institution.province + "' "
            + "data-city='" + institution.city + "' "
            + "data-county='" + institution.county + "'>"
            + institution.name + "</option>");
        $("#inspectorPowerSelectUpdate").append("<option value='" + institution.name + "' "
            + "data-healinstitution_id='" + institution.id + "' "
            + "data-institution_id='" + institution.institutionId + "' "
            + "data-province='" + institution.province + "' "
            + "data-city='" + institution.city + "' "
            + "data-county='" + institution.county + "'>"
            + institution.name + "</option>");
    }
}

//添加账号
function saveAccount() {
    //获取参数
    let params = getSaveAccountParams();
    if (params) {
        WeKnow.loading();
        //请求接口
        $.ajax({
            type: "POST",
            url: "accountManage.do/saveAccount",
            dataType: "json",
            data: JSON.stringify(params),
            contentType: "application/json",
            async: true,//异步调用
            success: function (data) {
                WeKnow.closeLoading();
                if (data.errCode == 1) {
                    //请求成功重新加载页面
                    window.location.reload();
                } else if (data.errCode == -1) {
                    window.parent.WeKnow.location("loginTimeout");
                } else {
                    WeKnow.errorMsg(data.errMsg);
                }
            }
        });
    }
}

//获取 加载数据集合 入参
function getSaveAccountParams() {
    let params = {};
    params.loginUser = $("#loginUser").val();//账号名称
    params.loginPassword = $("#loginPassword").val();//账号密码
    params.name = $("#name").val();//用户姓名
    params.phone = $("#phone").val();//用户手机
    params.roleId = $("[name='roleId']:checked").val();//身份
    //校验参数
    if (!params.loginUser || !params.loginPassword || !params.name || !params.phone) {
        WeKnow.notifyMsg("参数不能为空")
        return null;
    }
    if (params.loginUser.length < 4 || params.loginUser.length > 16) {
        WeKnow.notifyMsg("请输入4-16位账号名称");
        return null;
    }
    if (params.loginPassword.length < 6 || params.loginPassword.length > 16) {
        WeKnow.notifyMsg("请输入6-16位账号密码");
        return null;
    }
    if (params.name.length < 2 || params.name.length > 16) {
        WeKnow.notifyMsg("请输入2-16位用户姓名");
        return null;
    }
    if (params.phone.length != 11) {
        WeKnow.notifyMsg("请输入11位用户手机");
        return null;
    }
    //身份
    if (params.roleId == 1) {
        //管理员 获取监管区域
        params.institutionId = $(".adminPowerSelect").val();
        if (!params.institutionId) {
            WeKnow.notifyMsg("监管区域不正确");
            return null;
        }
    } else {
        //监督员 获取监管机构集合
        let institutionList = $("[name='removeInstitution']");
        if (!institutionList || institutionList.length == 0) {
            WeKnow.notifyMsg("请添加监管机构");
            return null;
        }
        let institutionListData = [];
        for (let i = 0; i < institutionList.length; i++) {
            let institution = $(institutionList[i]);
            let institutionData = {};
            institutionData.institutionId = institution.data("institution_id");
            institutionData.addressId = institution.data("address_id");
            institutionData.province = institution.data("province");
            institutionData.city = institution.data("city");
            institutionData.county = institution.data("county");
            institutionListData.push(institutionData);
        }
        params.institutionList = institutionListData;
    }
    return params;
}

//获取当前权限机构
function getJurisdictionInstitution(supervisorId) {
    WeKnow.loading();
    $.ajax({
        type: "POST",
        url: "accountManage.do/getJurisdictionInstitution",
        dataType: "json",
        data: {
            "supervisorId": supervisorId
        },
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //清空
                let ListDiv = $(".confirmInstitutionListDivUpdate");
                ListDiv.html("");
                //请求成功遍历数据添加到选中
                let enforcementList = data.enforcementList;
                for (let i = 0; i < enforcementList.length; i++) {
                    let enforcement = enforcementList[i];
                    //添加监管机构到页面
                    let html = '<div class="confirmInstitutionDiv">'
                        + '<input type="text" class="inspectorPowerIpt" readonly value="' + enforcement.institutionName + '">'
                        + '<input class="btn btn-primary confirmInstitution" name="removeInstitution" '
                        + 'data-institution_id="' + enforcement.institutionId + '" '
                        + 'data-address_id="' + enforcement.addressId + '" '
                        + 'data-province="' + enforcement.province + '" '
                        + 'data-city="' + enforcement.city + '" '
                        + 'data-county="' + enforcement.county + '" '
                        + 'data-name="' + enforcement.addressName + ' ' + enforcement.institutionName + '" '
                        + 'type="button" value="×">'
                        + '</div>';
                    ListDiv.append(html);
                    //从下拉列表中删除
                    let selectOption = $(".inspectorPowerSelectUpdate option[value = '" + enforcement.institutionId + "']");
                    selectOption.remove();
                }
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });
}

//保存账号权限修改
function updateAccount() {
    let params = {};
    //获取参数
    params.id = $("#updateAccountId").val();
    params.roleId = $("#updateRoleId").val();
    //身份
    if (params.roleId == 1) {
        //管理员 获取监管区域
        params.institutionId = $(".adminPowerSelectUpdate").val();
        if (!params.institutionId) {
            WeKnow.notifyMsg("监管区域不正确");
            return null;
        }
    } else {
        //监督员 获取监管机构集合
        let institutionList = $("[name='removeInstitution']");
        if (!institutionList || institutionList.length == 0) {
            WeKnow.notifyMsg("请添加监管机构");
            return null;
        }
        let institutionListData = [];
        for (let i = 0; i < institutionList.length; i++) {
            let institution = $(institutionList[i]);
            let institutionData = {};
            institutionData.institutionId = institution.data("institution_id");
            institutionData.addressId = institution.data("address_id");
            institutionData.province = institution.data("province");
            institutionData.city = institution.data("city");
            institutionData.county = institution.data("county");
            institutionListData.push(institutionData);
        }
        params.institutionList = institutionListData;
    }
    WeKnow.loading();
    //请求接口
    $.ajax({
        type: "POST",
        url: "accountManage.do/updateAccount",
        dataType: "json",
        data: JSON.stringify(params),
        contentType: "application/json",
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //请求成功重新加载页面
                window.location.reload();
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });

}

function bindAccount() {

    let params = {};
    //获取参数
    params.bindSupervisorId = $("#bindSupervisorId").val();
    params.encryptUid = $("#encryptUid").val();

    WeKnow.loading();
    //请求接口
    $.ajax({
        type: "POST",
        url: "accountManage.do/bindAccount",
        dataType: "json",
        data: params,
        async: true,//异步调用
        success: function (data) {
            WeKnow.closeLoading();
            if (data.errCode == 1) {
                //请求成功重新加载页面
                window.location.reload();
            } else if (data.errCode == -1) {
                window.parent.WeKnow.location("loginTimeout");
            } else {
                WeKnow.errorMsg(data.errMsg);
            }
        }
    });


}

